<template>
  <div class="community-posts-page">
    <div class="page-header">
      <div class="header-content">
        <h1>帖子列表</h1>
        <p>分享你的想法，与社群成员交流互动</p>
      </div>
      <div class="header-actions">
        <el-button v-if="!isAdminMode" type="primary" @click="showCreatePostDialog = true">
          <el-icon><Plus /></el-icon>
          发布帖子
        </el-button>
        <el-button @click="$router.go(-1)">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-container">
      <div v-if="posts.length === 0" class="empty-state">
        <el-icon :size="64"><ChatDotRound /></el-icon>
        <h3>暂无帖子</h3>
        <p v-if="!isAdminMode">发布第一个帖子，开始社群交流吧！</p>
        <el-button v-if="!isAdminMode" type="primary" @click="showCreatePostDialog = true">
          发布帖子
        </el-button>
      </div>
      
      <div v-else class="posts-list">
        <div 
          class="post-item" 
          v-for="post in posts" 
          :key="post.id"
        >
          <div class="post-header">
            <div class="post-author">
              <el-avatar :size="40">
                {{ post.authorName.charAt(0) }}
              </el-avatar>
              <div class="author-info">
                <div class="author-name">{{ post.authorName }}</div>
                <div class="post-time">{{ formatTime(post.createTime) }}</div>
              </div>
            </div>
            <div class="post-actions">
              <el-button 
                v-if="isAdminMode || String(post.authorId) === userInfo.id || String(currentCommunity?.creatorId) === userInfo.id"
                size="small" 
                type="danger" 
                @click="deletePost(post)"
              >
                删除
              </el-button>
              <el-button size="small" @click="viewPostDetail(post)">
                查看详情
              </el-button>
            </div>
          </div>
          
          <div class="post-content">
            <h3 class="post-title">{{ post.title }}</h3>
            <p class="post-text">{{ post.content }}</p>
          </div>
          
          <div class="post-footer">
            <div class="post-stats">
              <span>{{ post.viewCount }} 浏览</span>
              <span>{{ post.commentCount }} 评论</span>
            </div>
            <div class="post-actions">
              <el-button 
                size="small" 
                :type="post.isLiked ? 'primary' : 'default'"
                @click="toggleLike(post)"
              >
                <el-icon><ThumbsUp /></el-icon>
                {{ post.likeCount }} 点赞
              </el-button>
              <el-button size="small" @click="showComments(post)">
                <el-icon><ChatDotRound /></el-icon>
                评论
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 发布帖子对话框 -->
    <el-dialog 
      v-model="showCreatePostDialog" 
      title="发布帖子" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="createPostFormRef" 
        :model="createPostForm" 
        :rules="createPostRules" 
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="createPostForm.title" 
            placeholder="请输入帖子标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="createPostForm.content" 
            type="textarea" 
            :rows="6"
            placeholder="请输入帖子内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            action="/api/community-post/upload-image"
            list-type="picture-card"
            :on-success="handleImageUploadSuccess"
            :on-remove="handleImageRemove"
            :file-list="imageFileList"
            :headers="uploadHeaders"
            :multiple="true"
            :limit="9"
            :accept="'image/*'"
            name="files"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">支持多张图片，单张不超过5MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreatePostDialog = false">取消</el-button>
        <el-button type="primary" @click="createPost" :loading="creating">
          发布
        </el-button>
      </template>
    </el-dialog>

    <!-- 评论对话框 -->
    <el-dialog 
      v-model="showCommentsDialog" 
      :title="`${currentPost?.title} - 评论`" 
      width="600px"
    >
      <div class="comments-section">
        <div class="comment-input">
          <el-input 
            v-model="commentContent" 
            type="textarea" 
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          />
          <el-button 
            type="primary" 
            @click="addComment(commentContent, null)"
            :loading="commenting"
            style="margin-top: 12px;"
          >
            发表评论
          </el-button>
        </div>
        <div class="comments-list">
          <div v-if="comments.length === 0" class="empty-comments">
            <p>暂无评论，快来发表第一条评论吧！</p>
          </div>
          <div v-else>
            <CommentItem
              v-for="comment in comments"
              :key="comment.id"
              :comment="comment"
              :userInfo="userInfo"
              :postAuthorId="currentPost?.authorId"
              :formatTime="formatTime"
              :deleteComment="deleteComment"
              :toggleCommentLike="toggleCommentLike"
              :addComment="addComment"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 帖子详情弹窗 -->
    <el-dialog v-model="showDetailDialog" title="帖子详情" width="600px" :close-on-click-modal="false" @close="closeDetailDialog">
      <div v-if="loadingDetail" style="text-align:center;padding:40px 0;">
        <el-icon><Loading /></el-icon>
        加载中...
      </div>
      <div v-else-if="detailPost">
        <div style="margin-bottom:16px;">
          <el-carousel v-if="detailPost.images && JSON.parse(detailPost.images).length > 0" height="300px" :interval="5000" arrow="always">
            <el-carousel-item v-for="(img, idx) in JSON.parse(detailPost.images)" :key="idx">
              <el-image :src="resolveImageUrl(img)" style="width:100%;height:300px;object-fit:contain;" fit="contain" />
            </el-carousel-item>
          </el-carousel>
        </div>
        <h2>{{ detailPost.title }}</h2>
        <div style="color:#888;font-size:14px;margin-bottom:8px;">
          作者：{{ detailPost.authorName }}
          <span style="margin-left:16px;">{{ formatTime(detailPost.createTime) }}</span>
        </div>
        <div style="margin-bottom:12px;">{{ detailPost.content }}</div>
        <div style="color:#888;font-size:14px;">浏览量：{{ detailPost.viewCount }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Back,
  ChatDotRound,
  ThumbsUp,
  Loading
} from '@element-plus/icons-vue'
import { communityPostApi } from '@/api/social'
import { resolveAvatarUrl } from '@/utils/avatar'
import CommentItem from '@/components/CommentItem.vue'
import resolveImageUrl from '@/utils/resolveImageUrl'

export default {
  name: 'CommunityPostsPage',
  components: {
    Plus,
    Back,
    ChatDotRound,
    ThumbsUp,
    Loading,
    CommentItem
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    
    // 用户信息
    const userInfo = computed(() => store.state.user.userInfo)
    
    // 社群信息
    const currentCommunity = ref(null)
    
    // 帖子数据
    const posts = ref([])
    
    // 对话框状态
    const showCreatePostDialog = ref(false)
    const showCommentsDialog = ref(false)
    
    // 创建帖子表单
    const createPostFormRef = ref()
    const createPostForm = reactive({
      title: '',
      content: '',
      images: []
    })
    
    const createPostRules = {
      title: [
        { required: true, message: '请输入帖子标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在2-100个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入帖子内容', trigger: 'blur' },
        { min: 5, max: 1000, message: '内容长度在5-1000个字符', trigger: 'blur' }
      ]
    }


    
    // 评论相关
    const currentPost = ref(null)
    const comments = ref([])
    const commentContent = ref('')
    const commenting = ref(false)
    const creating = ref(false)
    
    // 图片上传相关
    const imageFileList = ref([])
    const uploadHeaders = computed(() => ({
      'Authorization': `Bearer ${store.state.user.token}`
    }))
    const handleImageUploadSuccess = (response, file, fileList) => {
      if (response.code === 200 && response.data && response.data.length > 0) {
        // 只取本次上传的最后一张图片URL
        const url = response.data[response.data.length - 1]
        createPostForm.images.push(url)
        imageFileList.value = fileList
      } else {
        ElMessage.error('图片上传失败')
      }
    }
    const handleImageRemove = (file, fileList) => {
      // file.url为图片URL
      createPostForm.images = createPostForm.images.filter(url => url !== file.url)
      imageFileList.value = fileList
    }
    
    // 帖子详情弹窗相关
    const showDetailDialog = ref(false)
    const detailPost = ref(null)
    const loadingDetail = ref(false)
    const viewPostDetail = async (post) => {
      loadingDetail.value = true
      showDetailDialog.value = true
      try {
        const response = await communityPostApi.getPostDetail(post.id)
        if (response.code === 200) {
          detailPost.value = response.data
        } else {
          ElMessage.error(response.message || '获取帖子详情失败')
        }
      } catch (error) {
        ElMessage.error('获取帖子详情失败')
      } finally {
        loadingDetail.value = false
      }
    }
    const closeDetailDialog = () => {
      showDetailDialog.value = false
      detailPost.value = null
    }
    
    // 加载社群信息
    const loadCommunityInfo = async () => {
      try {
        const communityId = route.params.communityId
        // 暂时使用模拟数据，因为后端没有获取单个社群信息的接口
        currentCommunity.value = {
          id: communityId,
          name: '示例社群',
          creatorId: 1
        }
      } catch (error) {
        console.error('加载社群信息失败:', error)
        ElMessage.error('加载社群信息失败')
      }
    }
    
    // 加载帖子列表
    const loadPosts = async () => {
      try {
        const response = await communityPostApi.getCommunityPosts(currentCommunity.value.id)
        if (response.code === 200) {
          posts.value = response.data
        } else {
          ElMessage.error(response.message || '加载帖子失败')
        }
      } catch (error) {
        console.error('加载帖子失败:', error)
        ElMessage.error('加载帖子失败')
      }
    }
    
    // 发布帖子
    const createPost = async () => {
      try {
        await createPostFormRef.value.validate()
        creating.value = true
        const response = await communityPostApi.createPost({
          communityId: currentCommunity.value.id,
          title: createPostForm.title,
          content: createPostForm.content,
          images: JSON.stringify(createPostForm.images)
        })
        if (response.code === 200) {
          ElMessage.success('帖子发布成功')
          showCreatePostDialog.value = false
          createPostForm.title = ''
          createPostForm.content = ''
          createPostForm.images = []
          imageFileList.value = []
          await loadPosts()
        } else {
          ElMessage.error(response.message || '发布帖子失败')
        }
      } catch (error) {
        console.error('发布帖子失败:', error)
        ElMessage.error('发布帖子失败')
      } finally {
        creating.value = false
      }
    }
    
    // 删除帖子
    const deletePost = async (post) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这个帖子吗？',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await communityPostApi.deletePost(post.id)
        if (response.code === 200) {
          ElMessage.success('帖子删除成功')
          await loadPosts()
        } else {
          ElMessage.error(response.message || '删除帖子失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除帖子失败:', error)
          ElMessage.error('删除帖子失败')
        }
      }
    }
    
    // 点赞/取消点赞
    const toggleLike = async (post) => {
      try {
        const response = await communityPostApi.togglePostLike(post.id)
        if (response.code === 200) {
          post.isLiked = !post.isLiked
          post.likeCount += post.isLiked ? 1 : -1
          ElMessage.success(post.isLiked ? '点赞成功' : '取消点赞')
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
    
    // 组装评论树
    function buildCommentTree(flatComments) {
      const map = {}
      const roots = []
      flatComments.forEach(c => {
        c.children = []
        map[c.id] = c
      })
      flatComments.forEach(c => {
        if (c.parentId && map[c.parentId]) {
          map[c.parentId].children.push(c)
        } else {
          roots.push(c)
        }
      })
      return roots
    }
    
    // 显示评论
    const showComments = async (post) => {
      currentPost.value = post
      showCommentsDialog.value = true
      try {
        const response = await communityPostApi.getPostComments(post.id)
        if (response.code === 200) {
          comments.value = buildCommentTree(response.data)
        } else {
          ElMessage.error(response.message || '加载评论失败')
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        ElMessage.error('加载评论失败')
      }
    }
    
    // 添加评论/回复
    const addComment = async (content, parentId = null) => {
      if (!content.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }
      try {
        commenting.value = true
        const response = await communityPostApi.createComment({
          postId: currentPost.value.id,
          content,
          parentId
        })
        if (response.code === 200) {
          ElMessage.success('评论发表成功')
          // 重新加载评论树
          await showComments(currentPost.value)
        } else {
          ElMessage.error(response.message || '发表评论失败')
        }
      } catch (error) {
        console.error('发表评论失败:', error)
        ElMessage.error('发表评论失败')
      } finally {
        commenting.value = false
      }
    }
    
    // 删除评论
    const deleteComment = async (comment) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这条评论吗？',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await communityPostApi.deleteComment(comment.id)
        if (response.code === 200) {
          ElMessage.success('评论删除成功')
          await showComments(currentPost.value)
        } else {
          ElMessage.error(response.message || '删除评论失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除评论失败:', error)
          ElMessage.error('删除评论失败')
        }
      }
    }
    
    // 点赞/取消点赞评论
    const toggleCommentLike = async (comment) => {
      try {
        const response = await communityPostApi.toggleCommentLike(comment.id)
        if (response.code === 200) {
          comment.isLiked = !comment.isLiked
          comment.likeCount += comment.isLiked ? 1 : -1
          ElMessage.success(comment.isLiked ? '点赞成功' : '取消点赞')
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
    

    
    // 格式化时间
    const formatTime = (time) => {
      const date = new Date(time)
      return date.toLocaleString()
    }
    
    onMounted(() => {
      loadCommunityInfo()
      loadPosts()
    })
    
    // 判断是否为管理员模式
    const isAdminMode = computed(() => route.query.admin === '1' || route.query.admin === 1)
    
    return {
      userInfo,
      currentCommunity,
      posts,
      showCreatePostDialog,
      showCommentsDialog,
      createPostFormRef,
      createPostForm,
      createPostRules,

      currentPost,
      comments,
      commentContent,
      commenting,
      creating,
      loadPosts,
      createPost,
      deletePost,
      toggleLike,
      showComments,
      addComment,
      deleteComment,
      toggleCommentLike,
      formatTime,
      imageFileList,
      uploadHeaders,
      handleImageUploadSuccess,
      handleImageRemove,
      viewPostDetail,
      showDetailDialog,
      detailPost,
      loadingDetail,
      closeDetailDialog,
      resolveAvatarUrl,
      resolveImageUrl,
      isAdminMode
    }
  }
}
</script>

<style scoped>
.community-posts-page {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-content h1 {
  font-size: 28px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.header-content p {
  color: var(--el-text-color-regular);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.posts-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--el-text-color-secondary);
}

.empty-state h3 {
  margin: 16px 0 8px;
  color: var(--el-text-color-primary);
}

.empty-state p {
  margin-bottom: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.post-author {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.post-time {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.post-content {
  margin-bottom: 16px;
}

.post-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.post-text {
  color: var(--el-text-color-regular);
  line-height: 1.6;
  margin: 0;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-stats {
  display: flex;
  gap: 16px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.comments-section {
  max-height: 500px;
  overflow-y: auto;
}

.comment-input {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.empty-comments {
  text-align: center;
  padding: 40px;
  color: var(--el-text-color-secondary);
}

.comment-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.comment-content {
  color: var(--el-text-color-regular);
  line-height: 1.5;
  margin-bottom: 12px;
}

.comment-footer {
  display: flex;
  justify-content: flex-end;
}

.comment-time {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}
</style> 